import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart';
import 'common_dialog.dart';
import 'hud_util.dart';

class ShareToWxDelegate {
  static final ShareToWxDelegate _instance = ShareToWxDelegate._internal();

  factory ShareToWxDelegate.getInstance() {
    return _instance;
  }

  ShareToWxDelegate._internal();

  // void init() {
  //   print('ShareToWxDelegate init');
  //   var appid;
  //   registerWxApi(appId: ApiConfig.env == ServerEnv.Product ? JxConstant.WeChatAppId : JxConstant.TestWeChatAppId(), doOnAndroid: true, doOnIOS: true, universalLink: "https://www.jxcloud.net.cn/");
  // }

  void listen() {
    weChatResponseEventHandler.listen((res) {
      if (res is WeChatShareResponse) {}
    });
  }

  /// 分享弹窗 shareType：0：小程序  1：图片  2：网页链接
  void showSharePop(BuildContext context, {Function? onTapFriend, Function? onTapCircle}) {
    DialogDelegate.showBottomPop(context, '分享',
        height: 220,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              children: [
                const Spacer(),
                GestureDetector(
                  onTap: () {
                    onTapFriend?.call();
                  },
                  child: Column(
                    children: [
                      Image.asset("assets/png/other/share_wx.png", height: 50, width: 50,),
                      const SizedBox(height: 5),
                      const Text('微信好友', style: TextStyle(fontSize: 11, color: Color(0XFF666666)),),
                    ],
                  ),
                ),
                const Spacer(),
                if (onTapCircle != null)
                  GestureDetector(
                    onTap: () {
                      onTapCircle.call();
                    },
                    child: Column(
                      children: [
                        Image.asset("assets/png/other/share_wx_circle.png", height: 50, width: 50,),
                        const SizedBox(height: 5),
                        const Text('微信朋友圈', style: TextStyle(fontSize: 11, color: Color(0XFF666666)),),
                      ],
                    ),
                  ),
                if (onTapCircle == null)
                  const SizedBox(width: 50),
                const Spacer(),
              ],
            ),
          ],
        ));
  }

  /// 分享小程序
  void doShareMiniProgram(String title, String imageCover, String allPath) {

    /// 只处理图片
    if (!imageCover.contains("?x-oss-process=video/snapshot")) {
      Image image = Image.network(imageCover);
      image.image.resolve(new ImageConfiguration()).addListener(new ImageStreamListener(
        (ImageInfo info, bool _) {
          num width = info.image.width.floor();
          num height = info.image.height.floor();
          if (width != null && height != null) {
            // if (width / height > 5 / 4) {
            //   imageCover = "$imageCover?x-oss-process=image/resize,m_pad,h_${(width * 0.8).floor()},w_$width,color_FFFFFF";
            // } else if (width / height < 5 / 4) {
            //   imageCover = "$imageCover?x-oss-process=image/resize,m_pad,h_$height,w_${(height * 1.25).floor()},color_FFFFFF";
            // }
            imageCover = "$imageCover?x-oss-process=image/resize,m_pad,h_400,w_500,color_FFFFFF";
            shareMiniProgram(title, imageCover, allPath);
          } else {
            HudUtil.toast("分享异常,请检查后重试");
          }
        },
      ));
    } else {
      shareMiniProgram(title, imageCover, allPath);
    }
  }

  shareMiniProgram(String title, String imageCover, String allPath) async {
    // WXMiniProgramType type = AppUtil.isProduct() ? WXMiniProgramType.RELEASE : WXMiniProgramType.PREVIEW;
    // LoggerUtil.logger.i(imageCover);

    var model = WeChatShareMiniProgramModel(
      webPageUrl: '',

      ///微信低版本的兼容链接，临时用
      miniProgramType: WXMiniProgramType.RELEASE,
      userName: '原始id',

      ///小程序原始ID
      title: title,
      description: '益捐',
      path: allPath,
      thumbnail: WeChatImage.network(imageCover),
    );
    shareToWeChat(model);
  }

  ///分享网页链接
  void doShareWebUrl(String webUrl, String title, String coverImg,
      {WeChatScene type = WeChatScene.TIMELINE, String? content}) async {
    var model = WeChatShareWebPageModel(webUrl,
        title: title,
        description: content ?? '益捐',
        scene: type,
        compressThumbnail: true,
        thumbnail: WeChatImage.network(coverImg));
    shareToWeChat(model);
  }

  void doSharePhotoWithFile(File file, bool toSession) async {
    WeChatImage weChatImage = WeChatImage.file(file);
    shareToWeChat(WeChatShareImageModel(weChatImage,
        scene: toSession ? WeChatScene.SESSION : WeChatScene.TIMELINE, description: 'IMAGE'));
  }

  void doSharePhotoWithUint8List(Uint8List images, bool toSession) async {
    WeChatImage weChatImage = WeChatImage.binary(images);
    shareToWeChat(WeChatShareImageModel(weChatImage,
        scene: toSession ? WeChatScene.SESSION : WeChatScene.TIMELINE, description: 'IMAGE'));
  }

  void doShareFile(File file, bool toSession) async {
    WeChatFile weChatFile = WeChatFile.file(file);
    shareToWeChat(WeChatShareFileModel(weChatFile,
        scene: toSession ? WeChatScene.SESSION : WeChatScene.TIMELINE, description: 'VIDEO'));
  }

  void doShareVideo(String videoUrl, bool toSession, String description) async {
    String coverUrl = "$videoUrl?x-oss-process=video/snapshot,t_100";
    WeChatImage weChatImage = WeChatImage.network(coverUrl);
    shareToWeChat(WeChatShareVideoModel(
        videoUrl: videoUrl,
        thumbnail: weChatImage,
        title: description,
        scene: toSession ? WeChatScene.SESSION : WeChatScene.TIMELINE,
        description: description));
  }

  ///跳转到权益微信小程序
  jumpMall(String path) {
    debugPrint("打开商城小程序");
    // WXMiniProgramType type = AppUtil.isProduct() ? WXMiniProgramType.RELEASE : WXMiniProgramType.PREVIEW;
    launchWeChatMiniProgram(username: "原始ID", path: path, miniProgramType: WXMiniProgramType.RELEASE);
  }
}
